import React, { useState, useEffect } from "react";
import http from "../utils/http";
import styles from "./Extension.module.css";
import { useNavigate } from "react-router-dom";

const Extension = () => {
    // 获取后端的数据
    const [list, setList] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(false);
    const router = useNavigate();

    const getdata = async () => {
        try {
            setLoading(true);
            setError(false);
            const res = await http.get("/listhjc");
            console.log("API返回数据:", res.data);

            // 使用res.data.list获取后端数据
            if (res.data && res.data.list) {
                // 如果res.data.list是数组，直接使用
                if (Array.isArray(res.data.list)) {
                    setList(res.data.list);
                } 
                // 如果res.data.list是单个对象，将其转换为数组
                else if (typeof res.data.list === 'object') {
                    setList([res.data.list]);
                } else {
                    setError(true);
                    console.warn("list数据格式不正确");
                }
            } else {
                console.warn("找不到list数据");
                setError(true);
            }
        } catch (error) {
            console.error("获取数据失败:", error);
            setList([]);
            setError(true);
        } finally {
            setLoading(false);
        }
    };

    // 用于副作用
    useEffect(() => {
        getdata();
    }, []);

    // 当list更新后打印数据
    useEffect(() => {
        console.log("当前list数据:", list);
    }, [list]);

    // 格式化日期函数
    const formatDate = (dateString) => {
        if (!dateString) return "";

        try {
            // 尝试解析日期字符串
            const date = new Date(dateString);
            if (isNaN(date.getTime())) {
                // 如果无法解析为日期，直接返回原字符串
                return dateString;
            }

            // 格式化为 YYYY-MM-DD 格式
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        } catch (e) {
            console.error("日期格式化错误:", e);
            return dateString;
        }
    };

    // 续住按钮点击事件
    const handleExtend = (hotel) => {
        if (hotel && hotel._id) {
            router(`/payment?id=${hotel._id}`);
        } else {
            alert("无效的房间数据");
        }
    };


    return (
        <div className={styles.container}>
            
            <div className="ljl-parking-header">
                <button className="ljl-back-button" onClick={()=>{router("/tabber/first")}}>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="30" height="30">
                        <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" />
                    </svg>
                </button>

                <h1 className="ljl-header-title">续住管理</h1>
                <div className="ljl-header-right">
                    <div className="ljl-dots-icon">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="24" height="24">
                            <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
                        </svg>
                    </div>
                </div>
            </div>
            
            <div className={styles.hotelList}>
                {loading ? (
                    <div className={styles.loading}>
                        <div className={styles.spinner}></div>
                        <p>加载中...</p>
                    </div>
                ) : error ? (
                    <div className={styles.errorMessage}>获取数据失败，请稍后重试</div>
                ) : list && list.length > 0 ? (
                    list.map((hotel, index) => (
                        <div key={index} className={styles.hotelCard}>
                            <div className={styles.hotelInfo}>
                                <div className={styles.guestInfo}>
                                    <div>
                                        <span className={styles.label}>在住客人: </span>
                                        <span className={styles.value}>{hotel.name || "未知客人"}</span>
                                    </div>
                                    <div>
                                        <span className={styles.roomNumber}>{hotel.room || "标准房"}</span>
                                    </div>
                                </div>

                                <div className={styles.bookingInfo}>
                                    {hotel.hname && (
                                        <div className={styles.bookingDetail}>
                                            <span className={styles.label}>酒店名称:</span>
                                            <span className={styles.value}>{hotel.hname}</span>
                                        </div>
                                    )}
                                    <div className={styles.bookingDetail}>
                                        <span className={styles.label}>抵店时间:</span>
                                        <span className={styles.value}>{formatDate(hotel.start)}</span>
                                    </div>
                                    <div className={styles.bookingDetail}>
                                        <span className={styles.label}>预离时间:</span>
                                        <span className={styles.value}>{formatDate(hotel.end)}</span>
                                    </div>
                                    <div className={styles.bookingDetail}>
                                        <span className={styles.label}>执行房价:</span>
                                        <span className={styles.price}>￥{hotel.price}</span>
                                    </div>
                                    
                                </div>

                                <div className={styles.availabilityInfo}>
                                    <div className={styles.daysLeft}>当前房间最长可续住: {hotel.day || 0}天</div>

                                    <button 
                                        className={styles.bookButton}
                                        onClick={() => handleExtend(hotel)}
                                        disabled={!hotel.day || hotel.day <= 0}
                                    >
                                        立即续住
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))
                ) : (
                    <div className={styles.emptyList}>暂无可用房间</div>
                )}
            </div>
        </div>
    );
};

export default Extension;